const Stock = require("../modules/Stock")

module.exports = async ({ code, type, ktype, latest, modifierList }) => {
    let result = { cycle: [], details: {} }

    ktype = ktype || "day"

    let hasModifierList = Array.isArray(modifierList) && modifierList.length

    let cycle = [
        { title: "15", ktype: "min15" },
        { title: "30", ktype: "min30" },
        { title: "60", ktype: "min60" },
        { title: "120", ktype: "min120" },
        { title: "日", ktype: "day" },
        { title: "周", ktype: "week" },
        { title: "月", ktype: "month" },
        { title: "季", ktype: "quarter" },
        { title: "年", ktype: "year" }
    ]

    if (hasModifierList) cycle = cycle.filter(item => item.ktype == ktype)

    let stock = new Stock({ code, type })

    let allSettled = []

    cycle.forEach((item) => {
        allSettled.push(new Promise(async resolve => {

            let transaction = await stock.getTransaction({ ktype: item.ktype })

            if (item.ktype == ktype && hasModifierList) {
                modifierList.forEach(item => {
                    if (item.type == "edit") {
                        transaction = Stock.editTransaction({ transaction, editTransaction: item.transaction })
                    }
                    if (item.type == "push") {
                        transaction = Stock.pushTransaction({ transaction, pushTransaction: item.transaction })
                    }
                })
            }

            let details = await stock.generateDetails({ transaction })

            // 最新 n 条交易数据
            let detailsLatest = Stock.getDetailsLatest({ details, latest })
            let divergence = Stock.divergence({ details: detailsLatest })
            let latestKd = Stock.latestKd({ details: detailsLatest })
            let latestMaDifference = Stock.latestMaDifference({ details: detailsLatest })

            detailsLatest.analysis = {
                divergence,
                latestKd,
                latestMaDifference
            }

            resolve(detailsLatest)
        }))
    })

    let cycleList = await Promise.allSettled(allSettled)

    result.cycle = cycleList.map(({ value: details }, index) => {
        let cycleItem = cycle[index]

        if (ktype == cycleItem.ktype) {
            result.details = details
        }
        else {
            delete details.transaction
        }

        delete details.calculate.macd.dea
        delete details.calculate.macd.diff
        delete details.calculate.kd.d

        return { ...cycleItem, details }
    })

    if (hasModifierList) result.cycle = []

    return result
}